﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ColdBootUnity
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			var container = new Microsoft.Practices.Unity.UnityContainer();
			container.AddExtension(new FactoryDefaultLifetime());

			var builder = container
				.AddNewExtension<Microsoft.Practices.Unity.StaticFactory.StaticFactoryExtension>()
				.Configure<Microsoft.Practices.Unity.StaticFactory.IStaticFactoryConfiguration>();

			builder.RegisterFactory<IWebApp>(
				c => new WebApp(
					c.Resolve<IAuthenticator>(),
					c.Resolve<IStockQuote>()));

			builder.RegisterFactory<IAuthenticator>(
				c => new Authenticator(
					c.Resolve<ILogger>(),
					c.Resolve<IErrorHandler>(),
					c.Resolve<IDatabase>()));

			builder.RegisterFactory<IStockQuote>(
				c => new StockQuote(
					c.Resolve<ILogger>(),
					c.Resolve<IErrorHandler>(),
					c.Resolve<IDatabase>()));

			builder.RegisterFactory<IDatabase>(
				c => new Database(
					c.Resolve<ILogger>(),
					c.Resolve<IErrorHandler>()));

			builder.RegisterFactory<IErrorHandler>(
				c => new ErrorHandler(c.Resolve<ILogger>()));

			builder.RegisterFactory<ILogger>(c => new Logger());


			Action action = () =>
			{
				var webApp = container.Resolve<IWebApp>();
				webApp.Run();
			};

			action();

			Close();
		}

		// Unbelievable complex to do such a simple thing...
		class FactoryDefaultLifetime : Microsoft.Practices.Unity.UnityContainerExtension
		{
			protected override void Initialize()
			{
				Context.Policies.SetDefault<Microsoft.Practices.ObjectBuilder2.ILifetimePolicy>(
					new Microsoft.Practices.ObjectBuilder2.TransientLifetimePolicy());
			}
		}
	}
}